package com.pickup.main;

import org.nfctools.ndef.NdefMessage;

import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.smartcardio.Card;
import javax.smartcardio.CardChannel;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import javax.smartcardio.TerminalFactory;

import static com.pickup.main.StringUtils.toByteArray;

class acr{

    static Timer timer;

    public static class RemindTask extends TimerTask {
        public void run() {
            CardRead();
        }
    }

    static String bin2hex(byte[] data) {
        return String.format("%0" + (data.length * 2) + "X", new BigInteger(1,data));
    }

    public static void CardRead() {
        TerminalFactory factory = TerminalFactory.getDefault();// 得到一個預設的讀卡器工廠(迷。。)
        List<CardTerminal> terminals;// 建立一個List用來放讀卡器(誰沒事會在電腦上插三四個讀卡器。。)
        try {
            terminals = factory.terminals().list();// 從工廠獲得插在電腦上的讀卡器列表,get讀卡器列表
            terminals.forEach(System.out::println);// 列印獲取到的讀卡器名稱

            CardTerminal cardTerminal = terminals.get(0);// 使用第0個讀卡器[暫且不考慮同時插N個讀卡器的情況了]
            cardTerminal.waitForCardPresent(0L);// 等待放置卡片
            Card card = cardTerminal.connect("T=1");// 連線卡片，協議T=1 塊讀寫(T=0貌似不支援，一用就報錯)
            CardChannel channel = card.getBasicChannel();// 開啟通道

            CommandAPDU getUID = new CommandAPDU(0xFF, 0xCA, 0x00, 0x00, 0x04);// 中文API第12頁
            ResponseAPDU r = channel.transmit(getUID);// 傳送getUID指令
            System.out.println("UID: " + r.toString());
            System.out.println("Data:" + StringUtils.toHexString(r.getData()));
            // 即返回卡號，操作成功
            StringBuilder stringBuilder = new StringBuilder();
            for (int n =4;n<=129;n+=4){
                CommandAPDU getData = new CommandAPDU(0xFF, 0xB0, 0x00, n , 0x10);// 構造 讀區塊APDU指令，中文API第17頁
                ResponseAPDU r1 = channel.transmit(getData);// 傳送 讀區塊指令
                stringBuilder.append(StringUtils.toHexString(r1.getData()));
            }
            String s = new String(toByteArray(stringBuilder.toString()));
            System.out.println(stringBuilder);
            System.out.println(s);
//            NdefMessage message = new NdefMessage(toByteArray(stringBuilder.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        timer = new Timer();
        timer.schedule(new acr.RemindTask(),1000L, 100L);
    }
}